<template>
  <el-dialog :title="title" :visible.sync="dialogFormVisible" :close-on-click-modal="false" :center=true >
    <el-form :model="book" :rules="rules" ref="ruleForm" >
      <el-form-item label="书名" :label-width="formLabelWidth" align="left"  prop="bookname">
        <el-input v-model="book.bookname" autocomplete="off" style="width:50%" ></el-input>
      </el-form-item>
      <el-form-item label="作者" :label-width="formLabelWidth" align="left" prop="authorname">
        <el-input v-model="book.authorname" autocomplete="off"  style="width:50%" ></el-input>
      </el-form-item>
      <el-form-item label="价格" :label-width="formLabelWidth" align="left" prop="price">
        <el-input v-model="book.price" autocomplete="off"  style="width:50%" ></el-input>
      </el-form-item>
      <el-form-item label="库存" :label-width="formLabelWidth" align="left" prop="inventory">
        <el-input v-model="book.inventory" autocomplete="off"  style="width:50%" ></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitf">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  data(){

    let check = (rule,value,callback)=>{
      if(!value){
        callback(new Error("此项不能为空！"))
      }else{
        callback()              // 一定要写这句!
      }
    };
    return {
      dialogFormVisible:false,    // 控制对话框的显示与隐藏
      formLabelWidth:'100px',     // 对话框标签宽度
      book:{},                 // 代表我们操作的学生
      title:'添加学生',            // 对话框的标题
      // 下面定义验证规则
      rules:{
        rules:{
          bookname:[{validator:check,trigger:blur}],
          authorname:[{validator:check,trigger:blur}],
          price:[{validator:check,trigger:blur}],
          inventory:[{validator:check,trigger:blur}],
        }
      }
    }
  },
  created() {

  },
  methods: {
    //组件初始化方法(供外界父组件调用)
    init() {
      //显示当前的对话框
      this.dialogFormVisible = true;

    },

    submitf() {

      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.dialogFormVisible = false
          this.add()
        } else {
          console.log('添加失败了呢')
          return false
        }
      })
    },
    //添加
    add() {
      let this1 = this
      let page = this.page
      let pagesize = this.pagesize
      let book = JSON.stringify(this.book);
      this.axios.post(`/book?cmd=add&book=${book}`).then(({data}) => {
        if (data) {
          this.$message({
            message: '添加成功咯！再查一下',
            type: 'success',
            onClose() {       // 关闭消息框时，刷新页面
              //刷新页面
              this1.findByPage(page, pagesize);
              this1.$emit("refreshBookDate")
            }
          })
        } else {
          console.log("数据库那边出现问题了T-T")
        }
      })
    }
  }}
</script>

<style scoped>

</style>